package com.justgame.project.base.interceptor;

import com.justgame.project.base.annotation.UploadApi;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.util.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * OSS保护拦截器 - Part of Request
 */
@Slf4j
@Component
@AllArgsConstructor
@ControllerAdvice("com.justgame.project.module.controller")
public class ProtectOssRequestInterceptor implements ResponseBodyAdvice<Result<?>> {

    @Resource
    private final RedisUtils redisUtils;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        if (method == null) return false;
        return method.isAnnotationPresent(UploadApi.class);
    }

    @Override
    public Result<?> beforeBodyWrite(Result<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null && body.getCode() != null && body.getCode() == 200) {
            if (body.getData() != null) {
                Map<Object, Object> fileObj = new HashMap<>();
                fileObj.put(body.getData(), TimeEnum.HOUR.calculateEndTimeFromNow(3));
                redisUtils.hSet(Const.KEY_TEMP_FILES, fileObj);
                log.info("\n已添加临时文件{}", body.getData());
            }
        }
        return body;
    }
}
